package org.itboys.mobile.service.mysql.mobile.order;

import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.mobile.dao.order.PearlOrderMapper;
import org.itboys.mobile.dao.order.PearlOrderProductMapper;
import org.itboys.mobile.entity.mysql.order.PearlOrder;
import org.itboys.mobile.entity.mysql.order.PearlOrderProduct;
import org.itboys.mobile.service.mongo.web.SundayMemberService;
import org.itboys.mobile.service.mysql.web.product.SundayProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created on 2017/10/23.
 * @author 朱坤涛
 * 订单工具，生产订单号，校验订单状态等等
 */
@Service
public class PearlOrderUtilService {
    public static String msg="请勿重复操作！";

    @Autowired
    private PearlOrderMapper orderMapper;
    @Autowired
    private SundayMemberService memberService;
    @Autowired
    private SundayProductService productService;
    @Autowired
    private PearlOrderProductMapper orderProductMapper;

    /**
     * 生成订单编号
     *  生成订单编号，示例：201510090000176,支持最大日订单数，10W-1，年月日+订单顺序+两位位随机数
     */
    public synchronized String generateOrderNo(){
        StringBuilder orderNo =new StringBuilder();
        Date now = new Date();
        String year = String.valueOf(now.getYear()+1900);
        String month= (now.getMonth()+1)<10?"0"+String.valueOf(now.getMonth()+1):String.valueOf(now.getMonth()+1);
        String day = now.getDate()<10?"0"+String.valueOf(now.getDate()):String.valueOf(now.getDate());
        //四位随机数
        String randomNumber = getRandomCode(2);
        orderNo.append(year);
        orderNo.append(month);
        orderNo.append(day);
        //检查是否是第一个订单
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("orderNoLike", orderNo);
        List<PearlOrder> oldOrders= orderMapper.select(param);
        if(oldOrders == null ||oldOrders.size()<1){
            //生成当前日期第一个订单号
            orderNo.append("00001");
            orderNo.append(randomNumber);
        }else{
            //找到最大编号
            Long oldMaxPreffix = 0L;
            for(PearlOrder oldOrder:oldOrders){
                Long oldPreffix=Long.valueOf(oldOrder.getOrderNo().substring(8,oldOrder.getOrderNo().length()-2));
                if(oldPreffix>oldMaxPreffix){
                    oldMaxPreffix=oldPreffix;
                }
            }
            //检查最大编号是否超出限制.最大编号后缀 9999
            if(oldMaxPreffix==99999){
                throw new ErrorException("订单编号已经超过限制");
            }

            //加上前面的000
            StringBuilder newNo = new StringBuilder();
            String newNoStr = String.valueOf(oldMaxPreffix+1);
            for(int i =0;i<5-newNoStr.length();i++){
                newNo.append("0");
            }
            newNo.append(newNoStr);
            orderNo.append(newNo);
            orderNo.append(randomNumber);
        }

        return orderNo.toString();
    }

    //生成随机数
    public static String getRandomCode(int length){
        StringBuilder sb = new StringBuilder();
        for(int i=0;i<length;i++){
            Random random1 = new Random();
            sb.append(Math.abs(random1.nextInt(10)));
        }
        return sb.toString();
    }
    //检查当前的订单状态是否可操作
    public PearlOrder checkOrderSatus(Long orderId,Integer orderStatus){
        PearlOrder order = orderMapper.find(orderId);
        if(order.getOrderStatus()!=orderStatus){
            throw new ErrorException(msg);
        }
        return  order;
    }
    //加载订单商品
    public void setOrderProducts(List<PearlOrder> orders,Long memberId){
        List<Long> orderIds = new ArrayList<Long>();
        for(PearlOrder order:orders){
            orderIds.add(order.getId());
        }
        //找到所有的订单商品
        Map<String,Object> param = new HashMap<String, Object>();
        param.put("orderIds", orderIds);
        List<PearlOrderProduct> allOrderProducts=orderProductMapper.select(param);

        for(PearlOrder order:orders){
            //List<XlclOrderProduct> orderProducts= orderProductService.findByField("orderId", order.getId());
            List<PearlOrderProduct> orderProducts = new ArrayList<PearlOrderProduct>();
            //根据用户加载订单明细佣金信息
            for(PearlOrderProduct orderProduct:allOrderProducts){

                if(order.getId()==orderProduct.getOrderId()){

                    //根据用户加载佣金信息
                    if(LongUtil.isNotZreo(memberId)){
                        BigDecimal memberRebate =null;

                        //如果当前用户是订单中代理商。可能含代理商推荐佣金
                        if(memberId==order.getAgentId()){
                            memberRebate=orderProduct.getAgentRebate();
                            //如果当前用户是订单中代理商推荐人
                        }else if(memberId==order.getRecommendeAgentId()){
                            memberRebate=orderProduct.getRecommendeAgentRebate();
                            //如果当前用户是订单中门店。可能含代理商推荐佣金
                        }else if(memberId==order.getAgentId()){
                            memberRebate=orderProduct.getShopRebate();
                            //如果当前用户是订单中门店推荐人
                        }else if(memberId==order.getAgentId()){
                            memberRebate=orderProduct.getRecommendeShopRebate();
                            //如果当前用户是订单中推荐人
                        }else if(memberId==order.getAgentId()){
                            memberRebate=orderProduct.getRecommenderRebate();
                        }
                        orderProduct.setMemberRebate(memberRebate);
                    }
                    orderProducts.add(orderProduct);
                    continue;
                }
            }
            order.setOrderProducts(orderProducts);
        }
    }
    //组装订单商品
    public PearlOrder packgeOrderProduct(PearlOrder order){
        Map<String,Object> param = new HashMap<String, Object>();
        List<PearlOrderProduct> orderProducts=orderProductMapper.select(param);
        //for(XlclOrder order:orders){
        List<PearlOrderProduct> orderProducts2=new ArrayList<PearlOrderProduct>();
        for(PearlOrderProduct orderProduct:orderProducts){
            if(order.getId().longValue()==orderProduct.getOrderId().longValue()){
                orderProducts2.add(orderProduct);
            }

            //}
            order.setOrderProducts(orderProducts2);
        }
        return order;
    }
    /**
     * 待确认
     * @param order
     */
    //计算订单的收益
    public void countOrderIncome(PearlOrder order){

    }
}
